/*
* codeBy:CK<admin@knifecms.com>
* update:2013-03-30
*/
$(function(){
	jQuery.fn.extend({
		folderTree:function(opt){
			if(!opt){var opt={}};
			var $this = this;
			this.ctl       = opt.ctl;
			this.$jsonData = opt.data;
			var appendFolder = function(obj){
				if(!obj){obj=$this}
				var json = $.parseJSON($this.$jsonData);
				if(json.folderexists=="false"){
					alert("KnifeCMS Error Message : Folder["+json.folderpath+"] Not Exists !");
				}else{
					var html  = "";
					if(opt.init==true){
					//第一次加载文件夹列表
						html = '<div class="folder open" folderpath="'+json.folderpath+'" subfolderscount="'+json.subfolderscount+'"><a href="javascript:;" class="node"></a><a href="javascript:;" class="foldername"><em></em>'+json.foldername+'</a></div>'
						obj.append(html);
						html = "";
						for(var i=0;i<json.subfolders.length;i++){
							html = html + '<div class="folder" folderpath="'+json.subfolders[i].folderpath+'" subfolderscount="'+json.subfolders[i].subfolderscount+'"><a href="javascript:;" class="node"></a><a href="javascript:;" class="foldername"><em></em>'+json.subfolders[i].foldername+'</a></div>'
						}
						obj.append('<div class="subfolders">'+html+'</div>');
					}else{
					//点击后加载文件夹列表
						for(var i=0;i<json.subfolders.length;i++){
							html = html + '<div class="folder" folderpath="'+json.subfolders[i].folderpath+'" subfolderscount="'+json.subfolders[i].subfolderscount+'"><a href="javascript:;" class="node"></a><a href="javascript:;" class="foldername"><em></em>'+json.subfolders[i].foldername+'</a></div>'
						}
						obj.append(html);
					}
				}
			}
			//生成子文件夹列表
			var createSubFolders = function(obj,_data){
				obj.find(".node").addClass("loading");
				var _$jsonData = _data || "";
				if(_$jsonData==""){
					var $url="ajax.get.asp?ctl="+$this.ctl+"&act=view&acttype=folderlist&folderpath="+escape(obj.attr("folderpath"))+"&r="+parseInt(Math.random()*1000);
					$.ajax({
						type:"POST",dataType:"html",async:true,url:$url,data:"",
						error:function(){alert(Lang_Js_Cue_ServerErrorAndTryLatter);},
						success:function(ajaxText){
							if(ajaxText.indexOf('identify="message"')>0){
								KnifeCMS.CreateDiaWindow(720,250,KnifeCMS.CreateID(),Lang_Js_DiaTitle[0],'<div class="message">'+ajaxText+'<div>',true,true);
							}else{
								obj.after('<div class="subfolders"></div>');
								obj.next(".subfolders").folderTree({data:ajaxText,init:false,ctl:$this.ctl});
							}
						}
					});
				}else{
					obj.after('<div class="subfolders"></div>');
					obj.next(".subfolders").folderTree({data:_$jsonData,init:false,ctl:$this.ctl});
				}
				obj.find(".node").removeClass("loading");
			}
			//生成文件树
			appendFolder();
			
			//遍历所有文件夹，去除没有子文件夹的文件展开图标
			$this.find(".folder").each(function(){
				if(parseInt($(this).attr("subfolderscount"))==0){
					$(this).find(".node").addClass("single");
				}
			});
			//点击文件夹获取子文件夹和文件列表
			$this.find(".foldername").click(function(){
				this.create = false;
				//取消其他同类文件夹的打开状态
				$this.find(".single").parent(".folder").removeClass("open");
				//判断是否需要生成子文件夹
				var folder = $(this).parent();
				var subFolders = folder.next(".subfolders").attr("class");
				if(subFolders==undefined){
					if(folder.find(".node").attr("class").indexOf("single")>0){
						create = false;
					}else{
						create = true;
					}
				}else{
					create = false;
				}
				//选中效果
				$("#foldertree").find(".folder").removeClass("current");
				folder.addClass("current");
				
				//显示子文件夹和文件列表
				var folderPath = $(this).parent().attr("folderpath");
				var $url="ajax.get.asp?ctl="+$this.ctl+"&act=view&acttype=subfolder_and_file_list&folderpath="+escape(folderPath)+"&r="+parseInt(Math.random()*1000);
				$.ajax({type:"POST",dataType:"html",async:true,url:$url,data:"",error:function(){alert(Lang_Js_Cue_ServerErrorAndTryLatter);},
						success:function(ajaxText){
							if(ajaxText.indexOf('identify="message"')>0){
								KnifeCMS.CreateDiaWindow(720,250,KnifeCMS.CreateID(),Lang_Js_DiaTitle[0],'<div class="message">'+ajaxText+'<div>',true,true);
							}else{
								var _json = $.parseJSON(ajaxText);
								var subFolders = _json[0];
								$this.$jsonData = KnifeCMS.JSON.toJSONString(subFolders);
								$("#filecontainer").fileManage({folderpath:folderPath,data:ajaxText,ctl:$this.ctl});
								//需要生成子文件夹
								if(create){
									createSubFolders(folder,$this.$jsonData);
								}
							}
						}
				});
				//展开子文件夹
				folder.addClass("open");
				folder.next(".subfolders").show("fast");
			});
			//点击展开或收缩起子文件夹列表
			$this.find(".node").click(function(){
				var folder     = $(this).parent();
				var subFolders = folder.next(".subfolders").attr("class");
				if(subFolders==undefined){
					createSubFolders(folder);
				}
				if(folder.attr("class").indexOf("open")>0){
					folder.removeClass("open");
					folder.next(".subfolders").hide("fast");
				}else{
					folder.addClass("open");
					folder.next(".subfolders").show("fast");
				}
			});
		}
	});
});

$(function(){
	jQuery.fn.extend({
		fileManage:function(opt){
			if(!opt){var opt={}};
			var $this = this;
			var $folderPath = opt.folderpath;
			this.ctl        = opt.ctl;
			this.$listType  = opt.listtype || KnifeCMS.Cookie.GetCookie("filelisttype") || "list";
			this.$jsonData  = opt.data || "";
			var fileExName = function(fileName){
				var array = fileName.split(".");
				return array[array.length-1];
			}
			var uploadFileType = function(){
				var array = $this.ctl.split("_");
				return array[1];
			}
			var listType = function(){
				var className = KnifeCMS.Cookie.GetCookie("filelisttype");
				if(className=="" || className==undefined){
					className = $this.$listType;
				}
				$(".listtype li").each(function(){
					if($(this).attr("listtype")==className){
						$(this).attr("class","current");
					}else{
						$(this).removeClass("current");
					}
				});
				$(".listtype li").click(function(){
					$this.$listType = $(this).attr("listtype");
					KnifeCMS.Cookie.SetCookie("filelisttype",$this.$listType);
					$(".listtype li").removeClass("current");
					$(this).addClass("current");
					$this.find("dl").attr("class",$this.$listType);
					foldersAndfilesPreview();
				});
			}
			var appendSubFoldersAndFiles = function(){
				$this.find(".filelist").html('<span class="loading_big">'+Lang_Js_Cue_DataLoading+'</span>');
				if($this.$jsonData==""){
					var $url="ajax.get.asp?ctl="+$this.ctl+"&act=view&acttype=subfolder_and_file_list&folderpath="+escape($folderPath)+"&r="+parseInt(Math.random()*1000);
					$.ajax({type:"POST",dataType:"html",async:true,url:$url,data:"",
					        error:function(){
								$("span.loading_big").remove();
								alert(Lang_Js_Cue_ServerErrorAndTryLatter);
							},
							success:function(ajaxText){
								$("span.loading_big").remove();
								if(ajaxText.indexOf('identify="message"')>0){
									KnifeCMS.CreateDiaWindow(720,250,KnifeCMS.CreateID(),Lang_Js_DiaTitle[0],'<div class="message">'+ajaxText+'<div>',true,true);
								}else{
									$this.$jsonData = ajaxText;
									_appendSubFoldersAndFiles();
								}
							}
					});
				}else{
					_appendSubFoldersAndFiles();
				}
			};
			var _appendSubFoldersAndFiles = function(){
				var dt,html,foldersHTML,filesHTML,json;
				json = $.parseJSON($this.$jsonData);
				$this.find(".filelist").html("");
				//列表头
				dt = "";
				dt = '<dt>'
				    +'<div class="checkbox"><input type="checkbox" name="selectall" value="" title="'+Lang_Js_SelectAll+'" /></div>'
				    +'<div class="name">'+Lang_Js_FileManage[1]+'</div><div class="datetime">'+Lang_Js_FileManage[2]+'</div>'
					+'<div class="size">'+Lang_Js_FileManage[3]+'</div>'
					+'</dt>';
				//显示文件夹列表
				foldersHTML = "";
				for(var i=0;i<json[0].subfolders.length;i++){
					foldersHTML = foldersHTML +'<dd class="folder" folderpath="'+json[0].subfolders[i].folderpath+'">'
								+'<div class="checkbox"><input type="checkbox" name="folder" value="'+json[0].subfolders[i].folderpath+'" title="'+Lang_Js_Select+'" /></div>'
								+'<div class="preview"></div>'
								+'<div class="name"><span class="icons_file icon_folder"></span><a href="javascript:;" title="'+json[0].subfolders[i].folderpath+'">'+json[0].subfolders[i].foldername+'</a></div>'
								+'<div class="datetime">'+json[0].subfolders[i].datetime+'</div>'
								+'<div class="size">'+json[0].subfolders[i].size+'</div>'
								+'</dd>'
				}
				//显示文件列表
				filesHTML = "";
				for(var i=0;i<json[1].files.length;i++){
					filesHTML = filesHTML +'<dd class="file" filepath="'+json[1].files[i].filepath+'">'
					            +'<div class="checkbox"><input type="checkbox" name="file" value="'+json[1].files[i].filepath+'" title="'+Lang_Js_Select+'" /></div>'
								+'<div class="preview"></div>'
								+'<div class="name"><span class="icons_file icon_file icon_'+uploadFileType()+' icon_file_'+fileExName(json[1].files[i].filepath)+'"></span><a href="javascript:;" title="'+json[1].files[i].filename+'">'+json[1].files[i].filename+'</a></div>'
								+'<div class="datetime">'+json[1].files[i].datetime+'</div>'
								+'<div class="size">'+json[1].files[i].size+'</div>'
								+'</dd>'
				}
				if($this.$listType=="thumb"){
					$this.find(".filelist").append('<dl class="thumb">'+ dt + foldersHTML + filesHTML +'</dl>');
					$this.find("dd.folder>.name>a").unbind("click");
				}else{
					$this.find(".filelist").append('<dl class="list">'+ dt + foldersHTML + filesHTML +'</dl>');
				}
				foldersAndfilesPreview();
				createFolderTagline(json[0].folderpath);

				//该文件夹为空
				if(json[0].subfolders.length + json[1].files.length == 0){
					$this.find(".filelist").html('<div class="none">'+Lang_Js_FileManage[4]+'</div>');
				}else{
					$this.find("#selectall").html('<input type="checkbox" name="selectall" value="" title="'+Lang_Js_SelectAll+'" /><label name="selectall">'+Lang_Js_SelectAll+'</label>')
				}
				//点击列表文件夹和文件则选中
				$this.find("dd").click(function(){
					var checkBox = $(this).find("input:checkbox");
					if(checkBox.attr("checked")==true){
						checkBox.attr("checked",false);
						$(this).removeClass("selected");
					}else{
						checkBox.attr("checked",true);
						$(this).addClass("selected");
					}
				});
				//点击文件夹名即可打开文件夹
				$this.find("dd.folder>.name>a").click(function(){
					$this.fileManage({folderpath:$(this).parent(".name").parent(".folder").attr("folderpath"),ctl:$this.ctl});
				});
				//双击文件夹栏也可打开文件夹
				$this.find("dd.folder").dblclick(function(){
					$this.fileManage({folderpath:$(this).attr("folderpath"),ctl:$this.ctl});
				});
				//点击全选
				$this.find("input[name='selectall']").click(function(){
					if($(this).attr("checked")==true){
						$this.find("dd input:checkbox").attr("checked",true);
						$this.find("dd").addClass("selected");
					}else{
						$this.find("dd input:checkbox").attr("checked",false);
						$this.find("dd").removeClass("selected");
					}
				});
				//删除按钮
				$this.find(".menuline>a[name='delete']").unbind("click");
				$this.find(".menuline>a[name='delete']").click(function(){deleteFoldersAndFiles($(this))});
				//冗余文件检测按钮
				$this.find(".menuline>a[name='filecheck']").unbind("click");
				$this.find(".menuline>a[name='filecheck']").click(function(){redundantFoldersAndFilesCheck($(this))});
				//文件打开
				$this.find("dd.file>.name>a").click(function(){
					fileView($(this).parent(".name").parent(".file").attr("filepath"));
				});
			}
			//设置按钮disabled为true或false状态
			var setButtonDisabled = function(obj,value){
				if(value==true){
					obj.attr("disabled",true);
					obj.addClass("disabled",true);
					obj.unbind("click");
				}else{
					obj.attr("disabled",false);
					obj.removeClass("disabled",true);
					obj.click(function(){deleteFoldersAndFiles($(this))});
				}
			}
			//切换列表方式时重构文件夹和文件显示方式
			var foldersAndfilesPreview = function(){
				if($this.$listType=="thumb"){
					$this.find("#selectall").show("fast");
					foldersPreview();
					filesPreview();
				}else{
					$this.find("#selectall").hide("fast");
				}
			}
			//文件夹缩略图预览
			var foldersPreview = function(){
				$this.find(".folder>.preview").each(function(){
					$(this).html('<span class="'+$(this).next().find("span").attr("class")+'"></span>');
				});
			}
			//文件缩略图预览
			var filesPreview = function(){
				$this.find(".file>.preview").each(function(){
					var filePath = $(this).parent(".file").attr("filepath");
					if($this.ctl=="file_image"){
						$(this).html('<img src="../'+filePath+'" />');
					}else{
						$(this).html('<span class="'+$(this).next().find("span").attr("class")+'"></span>');
					}
				});
			}
			//文件预览
			var fileView = function(filePath){
				var exName = fileExName(filePath);
				if(exName=="jpg" || exName=="jpe" || exName=="jpeg" || exName=="gif" || exName=="png" || exName=="bmp"){
					window.open("../"+filePath);
				}
			}
			//生成文件夹路径导航栏
			var createFolderTagline = function(_folderPath){
				var array = _folderPath.split("/");
				var folderPath = "", tagline = "", temp = "";
				for(var i=0; i<array.length; i++){
					if(array[i]!=""){
						folderPath  = folderPath + array[i] +'/';
						if(i>0){temp = temp +'<span class="folder"><a href="javascript:;" folderpath="'+folderPath+'">'+array[i]+'</a></span><span class="raquo">/</span>';}
					}
				}
				tagline = '<span class="folderroot"><em></em>'+Lang_Js_FileManage[5]+'</span><span class="raquo">/</span>'+temp+'';
				$this.find(".dirpath").html(tagline);
				//双击路径生成
				$this.find(".dirpath").find(".folder>a").click(function(){
					$this.fileManage({folderpath:$(this).attr("folderpath"),ctl:$this.ctl});
				});
			}
			//冗余文件检测
			var redundantFoldersAndFilesCheck = function(thisObj){
				//setButtonDisabled(thisObj,true);
				$this.find(".filelist").html('<span class="loading_big">'+Lang_Js_FileManage[9]+'</span>');
				var $url="ajax.get.asp?ctl="+$this.ctl+"&act=check&folderpath="+escape($folderPath)+"&r="+parseInt(Math.random()*1000);
				//window.open($url);
				$.ajax({type:"POST",dataType:"html",async:true,url:$url,data:"",
						error:function(){
							$("span.loading_big").remove();
							alert(Lang_Js_Cue_ServerErrorAndTryLatter);
						},
						success:function(ajaxText){
							//alert(ajaxText);
							$("span.loading_big").remove();
							if(ajaxText.indexOf('identify="message"')>0){
								KnifeCMS.CreateDiaWindow(720,250,KnifeCMS.CreateID(),Lang_Js_DiaTitle[0],'<div class="message">'+ajaxText+'<div>',true,true);
							}else{
								$this.$jsonData = ajaxText;
								
								//显示检测信息
								var _json   = $.parseJSON(ajaxText);
								var tipText = "";
								if((_json[0].subfolders.length+_json[1].files.length)>0){
									tipText = Lang_Js_FileManage[10].replace("{tpl:folderpath}",$folderPath);
									tipText = tipText.replace("{tpl:folderscount}",_json[0].subfolders.length);
									tipText = tipText.replace("{tpl:filescount}",_json[1].files.length);
								}else{
									tipText = Lang_Js_FileManage[11].replace("{tpl:folderpath}",$folderPath);
								}
								if(_json[2]!=undefined){
									tipText = tipText.replace("{tpl:runtime}",_json[2].runtime);
								}

								//显示冗余文件夹和文件
								_appendSubFoldersAndFiles();
								if($this.find(".filelist").find("dl").length==0){
									$this.find(".filelist").html("");
								}
								$this.find(".filelist").prepend('<div class="redundant_tip">'+ tipText +' </div>');
								
								//去除点击打开文件夹事件等
								$this.find("dd.folder>.name>a").each(function(){
									$(this).append('<em>('+$(this).parent(".name").parent("dd").attr("folderpath")+')</em>');
									$(this).addClass("disabled");
									$(this).unbind("click");
								});
								$this.find("dd.file>.name>a").each(function(){
									$(this).append('<em>('+$(this).parent(".name").parent("dd").attr("filepath")+')</em>');
								});
								//删除双击文件夹打开事件
								$this.find("dd.folder").unbind("dblclick");
							}
						}
				});
				//setButtonDisabled(thisObj,false);
			}
			//删除文件夹和文件
			var deleteFoldersAndFiles = function(thisObj){
				setButtonDisabled(thisObj,true);
				var temp,
				ii = 0,
				foldersJsonData = "",
				filesJsonData = "",
				jsonData = "";
				$this.find("input[name='folder']").each(function(i){
					if($(this).attr("checked")==true){
						ii++;
						if(foldersJsonData==""){
							foldersJsonData = '{"folderpath":"'+escape($(this).val())+'"}';
						}else{
							foldersJsonData = foldersJsonData +',{"folderpath":"'+escape($(this).val())+'"}';
						}
					}
				});
				$this.find("input[name='file']").each(function(i){
					if($(this).attr("checked")==true){
						ii++;
						if(filesJsonData==""){
							filesJsonData = '{"filepath":"'+escape($(this).val())+'"}';
						}else{
							filesJsonData = filesJsonData +',{"filepath":"'+escape($(this).val())+'"}';
						}
					}
				});
				if(ii==0){
					alert(Lang_Js_FileManage[6]);
				}else{
					if(confirm(Lang_Js_FileManage[12])){
						var dialogID = KnifeCMS.DiaDoing(Lang_Js_FileManage[7],true,true);
						jsonData = '{"folders":['+foldersJsonData+'],"files":['+filesJsonData+']}';
						var $url="ajax.get.asp?ctl="+$this.ctl+"&act=del&r="+parseInt(Math.random()*1000);
						$.ajax({type:"POST",dataType:"html",async:true,url:$url,data:"jsondata="+jsonData+"",
							error:function(){
								KnifeCMS.DiaWindowCloseByID(dialogID);
								alert(Lang_Js_Cue_ServerErrorAndTryLatter);
							},
							success:function(ajaxText){
								KnifeCMS.DiaWindowCloseByID(dialogID);
								if(ajaxText.indexOf('identify="message"')>0){
									var id = KnifeCMS.CreateID();
									KnifeCMS.CreateDiaWindow(720,250,KnifeCMS.CreateID(),Lang_Js_DiaTitle[0],'<div class="message">'+ajaxText+'<div>',true,true);
									$("div.DialogText").find("a").empty();
								}else{
									var json = $.parseJSON(ajaxText);
									for(var i=0; i<json.folders.length; i++){
										if(json.folders[i].deleteresult=="true"){
											//$("#filemanage").find(".folder[folderpath='"+json.folders[i].folderpath+"']").hide("slow");
											$("#filemanage").find(".folder[folderpath='"+json.folders[i].folderpath+"']").remove();
										}
									}
									for(var i=0; i<json.files.length; i++){
										if(json.files[i].deleteresult=="true"){
											//$("#filemanage").find(".file[filepath='"+json.files[i].filepath+"']").hide("slow");
											$("#filemanage").find(".file[filepath='"+json.files[i].filepath+"']").remove();
										}
									}
									KnifeCMS.DiaWindowCueMessage(Lang_Js_FileManage[8],4,280,128);
								}
							}
						});
					}
				}
				setButtonDisabled(thisObj,false);
			}
			listType();
			appendSubFoldersAndFiles();
		}
	});
});
